<template>
  <div>
    <div style="margin-bottom: 10px">

    </div>

    <div style="margin: 10px 0">
      <el-input style="width: 200px" placeholder="请输入名称" suffix-icon="el-icon-search" v-model="name"></el-input>
      <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
      <el-button class="ml-5" type="warning" @click="reset">重置</el-button>
    </div>

    <div style="margin: 10px 0">
      <el-button type="primary" @click="handleAddUser">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
      <el-popconfirm
          class="ml-5"
          confirm-button-text='好的'
          cancel-button-text='不用了'
          icon="el-icon-info"
          icon-color="red"
          title="确定删除吗？"
          @confirm="deleteMore"
      >
        <el-button type="danger" slot="reference">批量删除 <i class="el-icon-remove-outline"></i></el-button>
      </el-popconfirm>
    </div>

    <el-table :data="tableData" border stripe :header-cell-class-name="headerBg" style="font-size: 15px"
              @selection-change="handleSelectionChangeDeleteMore">
      >
      <el-table-column type="selection"></el-table-column>
      <el-table-column prop="id" label="序号" width="100"></el-table-column>
      <el-table-column prop="name" label="名称"></el-table-column>
      <el-table-column prop="description" label="描述"></el-table-column>

      <el-table-column label="操作" width="300" align="center">
        <template slot-scope="scope">
          <el-button type="info" @click="selectMenu(scope.row)">分配菜单 <i class="el-icon-menu"></i>
          </el-button>
          <el-button type="success" @click="handleEdit(scope.row)">编辑 <i class="el-icon-edit"></i></el-button>
          <el-popconfirm
              class="ml-5"
              confirm-button-text='好的'
              cancel-button-text='不用了'
              icon="el-icon-info"
              icon-color="red"
              title="确定删除吗？"
              @confirm="handleDelete(scope.row.id)">
            >
            <el-button type="danger" slot="reference">删除 <i class="el-icon-remove-outline"></i>
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <!--对话框弹出-->
    <el-dialog title="角色信息" :visible.sync="dialogFormVisible" width="30%">
      <el-form label-width="120px">
        <el-form-item label="名称">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser">确 定</el-button>
      </div>
    </el-dialog>

    <!--    菜单对话框-->
    <el-dialog title="菜单分配" :visible.sync="menuDialogVis" width="30%">
      <el-tree
          :props="props"
          :data="menuData"
          show-checkbox
          node-key="id"
          ref="tree"
          :default-expanded-keys="expends"
          :default-checked-keys="checks">
         <span class="custom-tree-node" slot-scope="{ node, data }">
            <span><i :class="data.icon"></i> {{ data.name }}</span>
         </span>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="menuDialogVis = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleMenu">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "User",
  data() {
    return {
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 5,
      name: '',
      // email: '',
      // address: '',
      // phone: '',
      form: [],//表单数据,
      menuData: [],//菜单数据
      props: {
        children: 'children',
        label: 'name',
        icon: 'icon'
      },//菜单树
      expends: [],//默认展开的菜单
      checks: [],//默认选中的菜单
      roleId: 0,//角色id
      multipleSelection: [],//多选
      dialogFormVisible: false,//对话框
      menuDialogVis: false,//菜单对话框
      headerBg: 'headerBg',
      roleFlag: '',//角色标识
    }
  },
  created() {
    this.load();
  },
  methods: {
    // 加载数据
    load() {
      this.request.get("/role/page", {
        // 参数
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name,
        }
      }).then(res => {
        this.tableData = res.data.records;
        this.total = res.data.total;
      })
    },
    //分页方法实现
    //页码
    handleSizeChange(pageSize) {
      console.log(pageSize)
      this.pageSize = pageSize
      this.load()
    },
    //页码
    handleCurrentChange(pageNum) {
      console.log(pageNum)
      this.pageNum = pageNum
      this.load()
    },
    //重置搜索按钮
    reset() {
      this.name = ''
      this.load()
    },
    //新增用户信息
    handleAddUser() {
      this.form = {
        username: '',
        nickname: '',
        email: '',
        address: '',
        phone: '',
      }
      this.dialogFormVisible = true;
    },
    //保存用户信息
    saveUser() {
      this.request.post("/role/saveOrUpdate", this.form).then(res => {
        if (res.code === '200') {
          this.$message.success('保存成功')
          this.dialogFormVisible = false;
          this.load()
        } else {
          this.$message.error('保存失败')
        }
      })
    },
    //编辑用户信息
    handleEdit(row) {
      this.dialogFormVisible = true;
      this.form = JSON.parse(JSON.stringify(row))  //可以解决编辑未确认就改变的问题

    },
    //删除用户信息
    handleDelete(id) {
      this.request.delete("/role/delOne/" + id).then(res => {
        if (res.code === '200') {
          this.$message.success('删除成功')
          this.load()
        } else {
          this.$message.error('删除失败')
        }
      })
    },
    //批量删除
    handleSelectionChangeDeleteMore(val) {
      console.log(val)
      this.multipleSelection = val
    },
    deleteMore() {
      let ids = this.multipleSelection.map(item => item.id)//[{},{}] => [1,2,3]
      this.request.post("/role/del/batch", ids).then(res => {
        if (res.code === '200') {
          this.$message.success('删除成功')
          this.load()
        } else {
          this.$message.error('删除失败')
        }
      })
    },
    //菜单分配
    async selectMenu(role) {
      this.menuDialogVis = true;
      this.roleId = role.id;
      this.roleFlag = role.flag;

      //请求菜单数据
      this.request.get("/menu").then(res => {
        this.menuData = res.data;
        //把后台返回的菜单数据处理成 id数组
        this.expends = this.menuData.map(item => item.id)
      })

      //请求角色已经分配的菜单
      this.request.get("/role-menu/roleMenu/" + this.roleId).then(res => {
        this.checks = res.data;
        this.menuDialogVis = true;
        this.request.get("/menu/ids").then(res => {
              const ids = res.data;
              ids.forEach(item => {
                if (!this.checks.includes(item)) {
                  this.$nextTick(() => {
                    this.$refs.tree.setChecked(item, false);
                  })

                }
              })
            }
        )

      })


      this.headerBg = 'headerBg'
      // this.request.get("/role/menu/all/" + row.id).then(res => {
      //   this.menuData = res.data
      // })
    },

    //保存 菜分配单
    saveRoleMenu() {
      //  console.log(this.$refs.tree.getCheckedKeys())
      // console.log(this.$refs.tree.getCheckedNodes())
      let menuIds = this.$refs.tree.getCheckedKeys()
      this.request.post("/role-menu/roleMenu/" + this.roleId, menuIds).then(res => {
        if (res.code === '200') {
          this.$message.success('保存成功')
          this.menuDialogVis = false;
          // 操作管理员角色后需要重新登录
          if (this.roleFlag === 'ROLE_ADMIN') {
            this.$store.commit("logout")
          }

        } else {
          this.$message.error('保存失败')
        }
      })

    }

  }
}
</script>

<style>
.headerBg {
  background: #eee !important;
}
</style>